package com.csdig.cms.service.impl;

import java.io.File;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.csdig.cms.common.ConstantDefine;
import com.csdig.cms.common.RealPathResolver;
import com.csdig.cms.dao.ContentDAO;
import com.csdig.cms.model.ext.ContentExt;
import com.csdig.cms.service.SiteMapService;
import com.csdig.cms.utils.BeanFactory;
import com.csdig.cms.utils.FrontUtils;
import com.csdig.cms.utils.OSUtils;
import com.redfin.sitemapgenerator.ChangeFreq;
import com.redfin.sitemapgenerator.SitemapGeneratorBuilder;
import com.redfin.sitemapgenerator.WebSitemapGenerator;
import com.redfin.sitemapgenerator.WebSitemapUrl;

@Service
public class SiteMapServiceImple implements SiteMapService {

	@Autowired
	private ContentDAO contentDao;

	@Autowired
	private RealPathResolver pathResolver;

	@Override
	public void genSiteMap(Integer[] channelIds) throws Exception {
		String baseUrl = FrontUtils.getDomain();
		if (!baseUrl.endsWith("/")) {
			baseUrl += "/";
		}
		WebSitemapGenerator wsg = newGenerator(baseUrl);
		for (Integer channelId : channelIds) {
			List<ContentExt> list = contentDao.findListForTag(channelId, 0, 300, " order by release_date desc");
			for (ContentExt content : list) {
				String url = baseUrl + content.getChannelUrl() + content.getLink()
						+ ConstantDefine.FrontPage.DYNAMIC_EXTENTION;
				WebSitemapUrl.Options op = new WebSitemapUrl.Options(url);
				op.priority(1.0d);
				op.changeFreq(ChangeFreq.HOURLY);
				op.lastMod(content.getReleaseDate());
				WebSitemapUrl websiteUrl = op.build();
				wsg.addUrl(websiteUrl);
			}
		}

		wsg.write();
	}

	private WebSitemapGenerator newGenerator(String baseUrl) throws Exception {
		File outputDir = null;
		if (OSUtils.isWindowOs()) {
			outputDir = new File(pathResolver.get("/"));
			// outputDir = new File("D:\\sitemap");
		} else {
			outputDir = new File("/opt/www/tucaobj/");
		}
		SitemapGeneratorBuilder<WebSitemapGenerator> sitemapGenBuilder = WebSitemapGenerator
				.builder(baseUrl, outputDir);
		sitemapGenBuilder.fileNamePrefix("sitemap");
		return sitemapGenBuilder.build();
	}

	public static void main(String[] args) throws Exception {
		SiteMapService sv = BeanFactory.getBeanByType(SiteMapService.class);
		sv.genSiteMap(new Integer[] { 9, 5, 7 });
	}

}
